import ctp.thosttraderapi as api
ctp_BC_config={
   'investor_id': '601230875',
   'broker_id':'0001',
   'password':'cc9200',
   'trader_server':'tcp://222.68.181.35:51205',
   'app_id':'client_bcjyhft_1.0.0',
   'auth_code':'EQC9HUWVKNE1Y8JV',
}
config=ctp_BC_config
FrontAddr=config['trader_server']
BROKERID=config['broker_id']
USERID=config['investor_id']
PASSWORD=config['password']
APPID=config['app_id']
AUTHCODE=config['auth_code']
orderfield=api.CThostFtdcInputOrderField()
orderfield.BrokerID=BROKERID
orderfield.ExchangeID='CZCE'
orderfield.InstrumentID='MA409'
orderfield.UserID=USERID
orderfield.InvestorID=USERID
orderfield.Direction='0'
orderfield.LimitPrice=0
orderfield.VolumeTotalOriginal=1
orderfield.OrderPriceType=api.THOST_FTDC_OPT_LimitPrice
orderfield.ContingentCondition = api.THOST_FTDC_CC_Immediately
orderfield.TimeCondition = api.THOST_FTDC_TC_GFD
orderfield.VolumeCondition = api.THOST_FTDC_VC_AV
orderfield.CombHedgeFlag=api.THOST_FTDC_HF_Speculation#投机，不是套保
        #TFtdcOffsetFlagEnType是一个开平标志类型
        #TFtdcOffsetFlagType是一个开平标志类型
orderfield.CombOffsetFlag=api.THOST_FTDC_OF_Open
orderfield.GTDDate=""
orderfield.orderfieldRef="1"
orderfield.MinVolume = 0
orderfield.ForceCloseReason = api.THOST_FTDC_FCC_NotForceClose
orderfield.IsAutoSuspend = 0
class CTradeSpi(api.CThostFtdcTraderSpi):
    tapi=''
    def __init__(self,tapi,orderfield):
        api.CThostFtdcTraderSpi.__init__(self)
        self.tapi=tapi
        # self.info=info
        self.orderfield=orderfield
    def OnRtnOrder(self, pOrder: 'CThostFtdcOrderField') -> "void":
        '''报单响应'''
        pass
    def OnRtnTrade(self,pTrade:'CThostFtdcTradeField' )-> "void":
        '''成交响应'''
        print("有成交，请查看上快期查看")
        
    def OnErrRtnOrderInsert(self,pInputOrder:'CThostFtdcInputOrderField', pRspInfo:'CThostFtdcRspInfoField')-> "void":
        print('1报单错误：',pRspInfo.ErrorMsg)

    def OnRspOrderInsert(self, pInputOrder: 'CThostFtdcInputOrderField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":      
        if pRspInfo.ErrorID!=0:
            print ("2报单错误：",pRspInfo.ErrorMsg)
    
    def OnRspOrderAction(self,pInputOrderAction:'CThostFtdcInputOrderActionField', pRspInfo:'CThostFtdcRspInfoField', nRequestID:'int',  bIsLast:'bool'):
        if pRspInfo.ErrorID!=0:
            print('撤单：',pRspInfo.ErrorMsg)
    def OnRspQryOrder(pOrder:'CThostFtdcOrderField', pRspInfo:'CThostFtdcRspInfoField', nRequestID:'int', bIsLast:'bool'):
        '''查询报单响应'''
        print(pOrder.InsertTime,'  ',pOrder.OrderSysID)
        # self.orderDict[pInputOrderAction.InstrumentID]['orderInQueue']['volume']=0
    def OnFrontDisconnected(nReason:'int'):
        print('断开连接,原因：',nReason)
    def orderSignalHandle(self,dc):
        pass
    def OnFrontConnected(self) -> "void":
        authfield = api.CThostFtdcReqAuthenticateField();
        authfield.BrokerID=BROKERID
        authfield.UserID=USERID
        authfield.AppID=APPID
        authfield.AuthCode=AUTHCODE
        self.tapi.ReqAuthenticate(authfield,0)
    
    def OnRspAuthenticate(self, pRspAuthenticateField: 'CThostFtdcRspAuthenticateField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":	
        if not pRspInfo.ErrorID :
            loginfield = api.CThostFtdcReqUserLoginField()
            loginfield.BrokerID=BROKERID
            loginfield.UserID=USERID
            loginfield.Password=PASSWORD
            loginfield.UserProductInfo="python dll"
            # print(pRspInfo.ErrorMsg)
            self.tapi.ReqUserLogin(loginfield,0)
        else:
            print('穿透式认证    失败')
            print ("BrokerID=",pRspAuthenticateField.BrokerID)
            print ("UserID=",pRspAuthenticateField.UserID)
            print ("AppID=",pRspAuthenticateField.AppID)
            print ("AppType=",pRspAuthenticateField.AppType)		
            print ("ErrorID=",pRspInfo.ErrorID)
            print ("ErrorMsg=",pRspInfo.ErrorMsg)
            exit()
        
    def OnRspUserLogin(self, pRspUserLogin: 'CThostFtdcRspUserLoginField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
        if pRspInfo.ErrorID:
            print("登陆   失败",pRspInfo.ErrorMsg)
            exit()
        else:#ErrorID==0
            print ("BrokerID:%s userID:%s"%(pRspUserLogin.BrokerID,pRspUserLogin.UserID))
            qryinfofield = api.CThostFtdcQrySettlementInfoField()
            qryinfofield.BrokerID=BROKERID
            qryinfofield.InvestorID=USERID
            qryinfofield.TradingDay=pRspUserLogin.TradingDay
            self.tapi.ReqQrySettlementInfo(qryinfofield,0)
            print("请求确认结算单")
        
    def OnRspQrySettlementInfo(self, pSettlementInfo: 'CThostFtdcSettlementInfoField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
        pSettlementInfoConfirm=api.CThostFtdcSettlementInfoConfirmField()
        pSettlementInfoConfirm.BrokerID=BROKERID
        pSettlementInfoConfirm.InvestorID=USERID
        self.tapi.ReqSettlementInfoConfirm(pSettlementInfoConfirm,0)
        
    def OnRspSettlementInfoConfirm(self, pSettlementInfoConfirm: 'CThostFtdcSettlementInfoConfirmField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
        if pRspInfo.ErrorID:
            print ("OnRspSettlementInfoConfirm")
            print ("ErrorID=",pRspInfo.ErrorID)
            print ("ErrorMsg=",pRspInfo.ErrorMsg)
            print ("send ReqorderfieldInsert ok")
            exit()
        else:
            print('确认结算单   成功')
        
    def ReqOrderInsert(self,InstrumentID,Direction=api.THOST_FTDC_D_Buy,LimitPrice=0,volume=1,CombOffsetFlag=api.THOST_FTDC_OF_Close):
        self.orderfield.InstrumentID=InstrumentID
        self.orderfield.Direction=Direction
        self.orderfield.VolumeTotalOriginal=volume  #LimitPrice
        self.orderfield.LimitPrice=LimitPrice
        self.orderfield.ExchangeID=self.info['instrumenID_dc'][InstrumentID]['exchange']
        self.orderfield.CombOffsetFlag=CombOffsetFlag     
        self.tapi.ReqOrderInsert(self.orderfield,0)
